using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpcuaClient.Model;

namespace OpcuaClient.Service
{
    public class ListViewService
    {
        public ListView ListView { get; set; }
        public ListViewService(ListView listView)
        {
            ListView = listView;
            ListView.Columns.Add("Key", "Key", 120);
            ListView.Columns.Add("Name", "名称", 150);
            ListView.Columns.Add("Address", "点位", 200);
        }
        /// <summary>
        /// 添加多个值 
        /// </summary>
        /// <param name="keyValues"></param>
        public void AddItems(List<ConstructionKeyValue> keyValues)
        {
            if (keyValues == null || keyValues.Count == 0)
            {
                return;
            }
            foreach (var item in keyValues)
            {
                if (item != null)
                {
                    AddItem(item);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyValue"></param>
        public void AddItem(ConstructionKeyValue keyValue)
        {
            if (keyValue == null) return;

            ListViewItem item = new ListViewItem();
            item.ImageIndex = ListView.Items.Count;
            item.Text = keyValue.Key;
            item.SubItems.Add(keyValue.Name);
            item.SubItems.Add(keyValue.Address);
            item.Tag = keyValue;

            ListView.BeginUpdate();
            bool sure = false;
            for (int i = 0; i < ListView.Items.Count; i++)
            {
                if (ListView.Items[i].Text == keyValue.Key)
                {
                    ListView.Items[i] = item;
                    sure = true;
                }
            }
            if (!sure)
            {
                ListView.Items.Add(item);
            }
            ListView.EndUpdate();
        }
    }
}
